import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Dimensions,
  Alert,
  Platform,
  Linking,
  PermissionsAndroid,
} from 'react-native';
import { RNCamera } from 'react-native-camera';

interface CustomQRScannerProps {
  onRead: (data: string) => void;
  onClose: () => void;
  flashMode?: any;
  cameraType?: 'front' | 'back';
}

const CustomQRScanner: React.FC<CustomQRScannerProps> = ({
  onRead,
  onClose,
  flashMode = RNCamera.Constants.FlashMode.auto,
  cameraType = 'back',
}) => {
  const [hasPermission, setHasPermission] = useState<boolean | null>(null);
  const [isAuthorized, setIsAuthorized] = useState(false);

  useEffect(() => {
    requestCameraPermission();
  }, []);

  const requestCameraPermission = async () => {
    try {
      console.log('=== 开始请求相机权限 ===');
      console.log('平台:', Platform.OS);

      if (Platform.OS === 'ios') {
        // iOS直接尝试使用相机，让系统自动处理权限
        console.log('iOS: 直接尝试使用相机...');
        setHasPermission(true);
        setIsAuthorized(true);
      } else {
        // Android权限请求
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.CAMERA,
          {
            title: '相机权限',
            message: '需要相机权限来扫描二维码',
            buttonNeutral: '稍后询问',
            buttonNegative: '取消',
            buttonPositive: '确定',
          }
        );

        console.log('Android权限请求结果:', granted);

        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          setHasPermission(true);
          setIsAuthorized(true);
        } else {
          setHasPermission(false);
          setIsAuthorized(false);
          showPermissionAlert();
        }
      }
    } catch (error) {
      console.error('请求相机权限失败:', error);
      setHasPermission(false);
      setIsAuthorized(false);
      showPermissionAlert();
    }
  };

  const showPermissionAlert = () => {
    Alert.alert(
      '相机权限',
      '需要相机权限才能使用扫码功能，请在设置中开启相机权限',
      [
        { text: '取消', onPress: onClose },
        {
          text: '设置',
          onPress: () => {
            // 打开系统设置
            if (Platform.OS === 'ios') {
              Linking.openURL('app-settings:');
            } else {
              Linking.openSettings();
            }
          }
        }
      ]
    );
  };

  const handleBarCodeRead = (event: any) => {
    const { data, type } = event;
    console.log('扫码结果:', { data, type });
    onRead(data);
  };

  const renderCamera = () => {
    if (!isAuthorized) {
      return (
        <View style={styles.noPermissionContainer}>
          <Text style={styles.noPermissionText}>相机未授权</Text>
          <TouchableOpacity style={styles.retryButton} onPress={requestCameraPermission}>
            <Text style={styles.retryButtonText}>重新授权</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.retryButton, { marginTop: 10, backgroundColor: '#666' }]}
            onPress={() => {
              if (Platform.OS === 'ios') {
                Linking.openURL('app-settings:');
              } else {
                Linking.openSettings();
              }
            }}
          >
            <Text style={styles.retryButtonText}>打开设置</Text>
          </TouchableOpacity>
        </View>
      );
    }

    return (
      <RNCamera
        style={styles.camera}
        type={cameraType}
        flashMode={flashMode}
        onBarCodeRead={handleBarCodeRead}
        captureAudio={false}
        androidCameraPermissionOptions={{
          title: '相机权限',
          message: '需要相机权限来扫描二维码',
          buttonPositive: '确定',
          buttonNegative: '取消',
        }}
      >
        <View style={styles.overlay}>
          <View style={styles.scanArea}>
            <View style={styles.cornerTL} />
            <View style={styles.cornerTR} />
            <View style={styles.cornerBL} />
            <View style={styles.cornerBR} />
          </View>
        </View>
      </RNCamera>
    );
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerText}>请扫描二维码</Text>
        <TouchableOpacity style={styles.closeButton} onPress={onClose}>
          <Text style={styles.closeButtonText}>关闭</Text>
        </TouchableOpacity>
      </View>

      <View style={styles.cameraContainer}>
        {renderCamera()}
      </View>

      <View style={styles.footer}>
        <Text style={styles.footerText}>将二维码放入框内即可自动扫描</Text>
      </View>
    </View>
  );
};

const { width, height } = Dimensions.get('window');
const scanAreaSize = Math.min(width, height) * 0.6;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingTop: 50,
    paddingBottom: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
  },
  headerText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
  },
  closeButton: {
    padding: 10,
  },
  closeButtonText: {
    color: '#007AFF',
    fontSize: 18,
  },
  cameraContainer: {
    flex: 1,
  },
  camera: {
    flex: 1,
  },
  overlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  scanArea: {
    width: scanAreaSize,
    height: scanAreaSize,
    position: 'relative',
  },
  cornerTL: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: 30,
    height: 30,
    borderTopWidth: 3,
    borderLeftWidth: 3,
    borderColor: '#00FF00',
  },
  cornerTR: {
    position: 'absolute',
    top: 0,
    right: 0,
    width: 30,
    height: 30,
    borderTopWidth: 3,
    borderRightWidth: 3,
    borderColor: '#00FF00',
  },
  cornerBL: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    width: 30,
    height: 30,
    borderBottomWidth: 3,
    borderLeftWidth: 3,
    borderColor: '#00FF00',
  },
  cornerBR: {
    position: 'absolute',
    bottom: 0,
    right: 0,
    width: 30,
    height: 30,
    borderBottomWidth: 3,
    borderRightWidth: 3,
    borderColor: '#00FF00',
  },
  footer: {
    padding: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.8)',
    alignItems: 'center',
  },
  footerText: {
    color: '#fff',
    fontSize: 14,
    textAlign: 'center',
  },
  noPermissionContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#000',
  },
  noPermissionText: {
    color: '#fff',
    fontSize: 16,
    marginBottom: 20,
  },
  retryButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  retryButtonText: {
    color: '#fff',
    fontSize: 16,
  },
});

export default CustomQRScanner; 